package com.swx.generate.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aspose.words.*;
import com.swx.generate.bean.*;
import com.swx.generate.dto.DownloadDTO;
import com.swx.generate.dto.ServerUrlDTO;
import com.swx.generate.exception.AppException;
import com.swx.generate.jmxBean.Argument;
import com.swx.generate.jmxBean.Header;
import com.swx.generate.jmxBean.TemplateBean;
import com.swx.generate.jmxBean.ThreadGroup;
import com.swx.generate.swagger.ApiDocTag;
import com.swx.generate.swagger.SwaggerResource;
import com.swx.generate.util.ConfigUtil;
import com.swx.generate.util.HttpUtil;
import com.swx.generate.util.WordUtil;
import com.swx.generate.util.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/")
public class generateController {

    private static final RestTemplate restTemplate = new RestTemplate();

    private String formatUrl(String serverUrl) {
        String[] strs = serverUrl.replaceAll("/", "").split(":");

        String protocol = "http";
        int deltaIndex = 0;

        if (strs.length == 3) {
            protocol = strs[0];
            deltaIndex = 1;
        }
        String port = strs[1 + deltaIndex];
        String domain = strs[deltaIndex];
        return protocol + "://" + domain + ":" + port;
    }

    @PostMapping("/generateJmxScript")
    public ApiResult<JSONObject> generateJmxScript(@RequestBody @Validated ServerUrlDTO serverUrlDTO) {
        String serverUrl = serverUrlDTO.getUrl();
        List<SwaggerResource> swaggerResources = getSwaggerResources(serverUrl);

        String[] strs = serverUrl.replaceAll("/", "").split(":");

        String protocol = "http";
        int deltaIndex = 0;

        if (strs.length == 3) {
            protocol = strs[0];
            deltaIndex = 1;
        }
        String port = strs[1 + deltaIndex];
        String domain = strs[deltaIndex];

        List<TemplateBean> templateBeans = new ArrayList<>();

        for (SwaggerResource swaggerResource : swaggerResources) {
            TemplateBean templateBean = new TemplateBean();
            templateBean.setGroupName(swaggerResource.getName());
            templateBean.setDomain(domain);
            templateBean.setPort(port);
            templateBean.setProtocol(protocol);
            List<Tag> tagList;
            try {
                tagList = getTagList(serverUrl, swaggerResource);
            } catch (Exception e) {
                log.error("【" + swaggerResource.getName() + "】获取接口信息失败");
                e.printStackTrace();
                continue;
            }

            List<ThreadGroup> threadGroupList = new ArrayList<>();
            for (Tag tag : tagList) {
                String name = tag.getName();
                List<Path> paths = tag.getPaths();
                ThreadGroup threadGroup = new ThreadGroup();
                threadGroup.setTestname(name);
                threadGroup.setHttpList(paths);
                threadGroupList.add(threadGroup);
            }
            templateBean.setThreadGroupList(threadGroupList);

            templateBeans.add(templateBean);
        }

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("jmxTemplate", ConfigUtil.getJmxTemplate());
        jsonObject.put("templateBeans", templateBeans);

        return ApiResult.success(jsonObject);
    }

    @PostMapping(value = "/generateJmxScriptFile")
    public ApiResult<String> generateJmxScriptFile(@RequestBody DownloadDTO downloadDTO) throws IOException {
        File outputDir = new File("output");
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        List<JmxStr> files = downloadDTO.getFiles();
        if (files == null || files.isEmpty()) {
            throw new RuntimeException("没有脚本可生成");
        }
        List<File> jmxList = new ArrayList<>();
        for (JmxStr jsonObject : files) {
            File jmxFile = new File("output" + File.separator + jsonObject.getName() + ".jmx");
            FileUtils.writeStringToFile(jmxFile, jsonObject.getJmxStr(), StandardCharsets.UTF_8);
            jmxList.add(jmxFile);
        }
        String fileName = downloadDTO.getServerUrl().replaceAll("[.:]", "_").replaceAll("/", "");
        File zipFile = new File("output" + File.separator + fileName + "-jmeter.zip");
        ZipUtil.zipFiles(zipFile, jmxList);
        for (File file : jmxList) {
            Files.deleteIfExists(file.toPath());
        }
        return ApiResult.success(zipFile.getCanonicalPath());
    }

    @GetMapping("/downloadFile")
    public void downloadFile(String filePath, HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(filePath)) {
            throw new RuntimeException("filePath不能为空");
        }
        File file = new File(filePath);
        if (!file.exists()) {
            throw new RuntimeException("【" + filePath + "】文件不存在");
        }

        // 开始下载
        response.setContentType("application/json;charset=utf-8");
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));
        byte[] buffer = FileUtils.readFileToByteArray(file);
        try (OutputStream outputStream = response.getOutputStream()) {
            outputStream.write(buffer);
        }
    }

    @PostMapping("/generateTestCase")
    public ApiResult<String> generateTestCase(@RequestBody @Validated ServerUrlDTO serverUrlDTO) throws Exception {
        String serverUrl = serverUrlDTO.getUrl();

        List<File> fileList = new ArrayList<>();
        List<ModuleItem> moduleList = getModuleList(serverUrl);

        for (ModuleItem moduleItem : moduleList) {
            Document doc = ConfigUtil.getTestcaseHeaderTemplateDoc().deepClone();
            Document interfaceDoc = ConfigUtil.getTestcaseBodyTemplateDoc().deepClone();

            List<CategoryItem> categoryList = moduleItem.getCategoryList();

            Map<String, Object> headerData = new HashMap<>();
            headerData.put("项目名称", moduleItem.getName());
            List<Map<String, Object>> testResult = new ArrayList<>();
            headerData.put("testResult", testResult);
            for (int i = 0; i < categoryList.size(); i++) {
                CategoryItem categoryItem = categoryList.get(i);
                Map<String, Object> map = new HashMap<>();
                map.put("编号", i + 1);
                map.put("服务名", categoryItem.getName());
                map.put("测试接口数", categoryItem.getPaths().size());
                testResult.add(map);
            }
            // 生成 header
            Document outDoc = WordUtil.fillWordByMap(doc, headerData);

            for (CategoryItem categoryItem : categoryList) {
                Section lastSection = outDoc.getLastSection();
                Body body = lastSection.getBody();
                Style style = outDoc.getStyles().get("标题 2");
                body.appendParagraph(categoryItem.getName()).getParagraphFormat().setStyle(style);
                List<CategoryItem.Path> paths = categoryItem.getPaths();
                for (CategoryItem.Path path : paths) {
                    Map<String, Object> data = new HashMap<>();

                    data.put("接口名称", path.getSummary());
                    data.put("接口地址", path.getUrl());

                    Document nodes = WordUtil.fillWordByMap(interfaceDoc, data);
                    outDoc = WordUtil.mergeDocument(outDoc, nodes);
                }
            }

            outDoc.updateFields();// 更新域
            String dstDocName = "output" + File.separator + moduleItem.getName() + "-接口测试用例.docx";
            outDoc.save(dstDocName);

            fileList.add(new File(dstDocName));
        }

        String fileName = serverUrl.replaceAll("[.:]", "_").replaceAll("/", "");
        File zipFile = new File("output" + File.separator + fileName + "-接口测试用例.zip");
        ZipUtil.zipFiles(zipFile, fileList);

        for (File file : fileList) {
            Files.deleteIfExists(file.toPath());
        }
        return ApiResult.success(zipFile.getCanonicalPath());
    }

    @PostMapping("/generateInterface")
    public ApiResult<String> generateInterface(@RequestBody @Validated ServerUrlDTO serverUrlDTO) throws IOException {
        String serverUrl = serverUrlDTO.getUrl();
        List<SwaggerResource> swaggerResources = getSwaggerResources(serverUrl);

        String[] strs = serverUrl.replaceAll("/", "").split(":");

        String protocol = "http";
        int deltaIndex = 0;

        if (strs.length == 3) {
            protocol = strs[0];
            deltaIndex = 1;
        }
        String port = strs[1 + deltaIndex];
        String domain = strs[deltaIndex];
        List<File> fileList = new ArrayList<>();
        for (SwaggerResource swaggerResource : swaggerResources) {
            TemplateBean templateBean = new TemplateBean();
            templateBean.setGroupName(swaggerResource.getName());
            templateBean.setDomain(domain);
            templateBean.setPort(port);
            templateBean.setProtocol(protocol);
            List<Tag> tagList;
            try {
                tagList = getTagList(serverUrl, swaggerResource);
            } catch (Exception e) {
                log.error("【" + swaggerResource.getName() + "】获取接口信息失败");
                e.printStackTrace();
                continue;
            }
            File file;
            try {
                file = generatoInterfacerWord(tagList, swaggerResource.getName());
            } catch (Exception e) {
                log.error("【" + swaggerResource.getName() + "】生成Word失败");
                e.printStackTrace();
                continue;
            }
            fileList.add(file);
        }
        String fileName = serverUrl.replaceAll("[.:]", "_").replaceAll("/", "");
        File zipFile = new File("output" + File.separator + fileName + "-接口设计文档.zip");
        ZipUtil.zipFiles(zipFile, fileList);

        for (File file : fileList) {
            file.delete();
        }
        return ApiResult.success(zipFile.getCanonicalPath());
    }

    private List<SwaggerResource> getSwaggerResources(String serverUrl) {
        JSONArray jsonArray = restTemplate.getForObject(serverUrl + "/swagger-resources", JSONArray.class);
        if (jsonArray == null) {
            throw new AppException("接口请求异常");
        }
        return jsonArray.toJavaList(SwaggerResource.class);
    }

    private List<Tag> getTagList(String serverUrl, SwaggerResource swaggerResource) {
        JSONObject apiDocs;
        try {
            apiDocs = restTemplate.getForObject(formatUrl(serverUrl) + swaggerResource.getUrl(), JSONObject.class);
        } catch (Exception e) {
            throw new RuntimeException("接口请求失败：" + formatUrl(serverUrl) + swaggerResource.getUrl());
        }

        JSONArray tags = apiDocs.getJSONArray("tags");
        if (tags == null) {
            throw new RuntimeException("没有获取到tags");
        }
        List<Tag> tagList = new ArrayList<>();
        for (int i = 0; i < tags.size(); i++) {
            JSONObject tagJSONObject = tags.getJSONObject(i);
            String tagName = tagJSONObject.getString("name");
            Optional<Tag> any = tagList.stream().filter(x -> tagName.equals(x.getName())).findAny();
            Tag tag;
            if (!any.isPresent()) {
                tag = new Tag();
                tag.setName(tagName);
                tagList.add(tag);
            }
        }
        JSONObject paths = apiDocs.getJSONObject("paths");

        JSONObject definitions = apiDocs.getJSONObject("definitions");
        String basePath = apiDocs.getString("basePath");
        if ("/".equals(basePath)) {
            basePath = "";
        }
        for (String url : paths.keySet()) {
            JSONObject pathJsonObject = paths.getJSONObject(url);
            for (String method : pathJsonObject.keySet()) {
                JSONObject jsonObject = pathJsonObject.getJSONObject(method);
                boolean deprecated = jsonObject.getBooleanValue("deprecated");
                if (deprecated) {
                    log.warn("接口【" + url + "】已过时");
                    continue;
                }

                String tagName = jsonObject.getJSONArray("tags").getString(0);

                Optional<Tag> any = tagList.stream().filter(x -> tagName.equals(x.getName())).findAny();
                if (!any.isPresent()) {
                    log.warn("没有找到名字为【" + tagName + "】的tag");
                    continue;
                }
                Tag tag = any.get();

                String summary = jsonObject.getString("summary");
                String description = jsonObject.getString("description");
                JSONArray consumes = jsonObject.getJSONArray("consumes");

                //                String consume = "";
                //                if (consumes != null) {
                //                    consume = consumes.getString(0);
                //                }

                Path path = new Path();

                tag.addPath(path);

                path.setUrl(basePath + url);
                path.setMethod(method.toUpperCase());
                path.setSummary(summary);
                path.setDescription(description);
                //                path.setConsumes(consume);

                //                // 处理接口输出
                //                JSONObject responses = jsonObject.getJSONObject("responses");
                //                JSONObject response200 = responses.getJSONObject("200");
                //                JSONObject responseSchema = response200.getJSONObject("schema");
                //                JSONObject responseProperty = new JSONObject();
                //                path.setRespones(responseProperty);
                //                if (responseSchema != null) {
                //                    String type = responseSchema.getString("type");
                //                    if (type == null) {
                //                        type = "";
                //                    }
                //                    switch (type) {
                //                        case "string":
                //                            path.setRespones(responseSchema.getString("format"));
                //                            break;
                //                        case "array":
                //                            Object example = null;
                //                            JSONObject itemSchema = responseSchema.getJSONObject("items");
                //                            String itemSchemaType = itemSchema.getString("type");
                //                            if (itemSchemaType == null) {
                //                                itemSchemaType = "";
                //                            }
                //                            switch (itemSchemaType) {
                //                                case "string":
                //                                    List<String> strArr = new ArrayList<>();
                //                                    strArr.add("");
                //                                    example = strArr;
                //                                    break;
                //                                case "object":
                //                                    example = new JSONObject();
                //                                    break;
                //                                case "integer":
                //                                    example = 0;
                //                                    break;
                //                                default:
                //                                    JSONArray defArr = new JSONArray();
                //                                    JSONObject item = new JSONObject();
                //                                    defArr.add(item);
                //                                    getProperty(itemSchema, definitions, item);
                //                                    example = defArr;
                //                                    break;
                //                            }
                //                            path.setRespones(example);
                //                            break;
                //                        case "object":
                //                            break;
                //                        case "boolean":
                //                            path.setRespones(true);
                //                            break;
                //                        case "integer":
                //                            path.setRespones(0);
                //                            break;
                //                        default:
                //                            getProperty(responseSchema, definitions, responseProperty);
                //                            break;
                //                    }
                //                }

                // 处理参数
                JSONObject property = new JSONObject();
                path.setProperties(property);

                JSONArray parameters = jsonObject.getJSONArray("parameters");
                if (parameters == null) {
                    continue;
                }

                if (consumes != null) {
                    //                    consume = consumes.getString(0);
                    Header header = new Header();
                    header.setName("content-type");
                    header.setValue(consumes.getString(0));
                    path.addHeader(header);
                }

                for (int i = 0; i < parameters.size(); i++) {
                    JSONObject parameter = parameters.getJSONObject(i);
                    String in = parameter.getString("in");
                    String name = parameter.getString("name");
                    switch (in) {
                        case "query":
                        case "formData":
                            String parameterType = parameter.getString("type");
                            if ("file".equals(parameterType)) {
                                com.swx.generate.jmxBean.File file = new com.swx.generate.jmxBean.File();
                                String xexample = parameter.getString("x-example");
                                if (xexample == null) {
                                    xexample = "";
                                }
                                file.setMimetype("multipart/form-data");
                                file.setParamname(name);
                                file.setPath(xexample);
                                path.addFile(file);
                                path.setBROWSER_COMPATIBLE_MULTIPART(true);
                                path.setDO_MULTIPART_POST(true);
                            } else if ("array".equals(parameterType)) {
                                JSONObject items = parameter.getJSONObject("items");
                                String itemType = items.getString("type");
                                if ("file".equals(itemType)) {
                                    com.swx.generate.jmxBean.File file = new com.swx.generate.jmxBean.File();
                                    String xexample = parameter.getString("x-example");
                                    if (xexample == null) {
                                        xexample = "";
                                    }
                                    file.setMimetype("multipart/form-data");
                                    file.setParamname(name);
                                    file.setPath(xexample);
                                    path.addFile(file);
                                    path.setBROWSER_COMPATIBLE_MULTIPART(true);
                                    path.setDO_MULTIPART_POST(true);
                                } else if ("string".equals(itemType)) {
                                    Argument argument = new Argument();
                                    argument.setName(name);
                                    argument.setValue("");
                                    path.addArgument(argument);
                                } else {
                                    JSONArray defArr = new JSONArray();
                                    JSONObject item = new JSONObject();
                                    defArr.add(item);

                                    items.getString("");

                                    getProperty("", definitions);

                                    Argument argument = new Argument();
                                    argument.setName(name);
                                    argument.setValue(JSON.toJSONString(defArr));
                                    path.addArgument(argument);
                                }
                            } else if ("string".equals(parameterType)) {
                                String xexample = parameter.getString("x-example");
                                if (xexample == null) {
                                    xexample = "";
                                }
                                Argument argument = new Argument();
                                argument.setName(name);
                                argument.setValue(xexample);
                                path.addArgument(argument);
                            } else {
                                Argument argument = new Argument();
                                argument.setName(name);
                                argument.setValue("");
                                path.addArgument(argument);
                            }
                            continue;
                        case "header":
                            String xexample = parameter.getString("x-example");
                            if (xexample == null) {
                                xexample = "";
                            }
                            Header header = new Header();
                            header.setName(name);
                            header.setValue(xexample);
                            path.addHeader(header);
                            continue;
                        case "body":
                            JSONObject schema = parameter.getJSONObject("schema");
                            String schemaType = schema.getString("type");
                            if ("string".equals(schemaType)) {
                                property.put(name, "");
                            } else if ("array".equals(schemaType)) {
                                JSONObject items = schema.getJSONObject("items");

                                String type = items.getString("type");
                                if ("string".equals(type)) {
                                    ArrayList<String> strings = new ArrayList<>();
                                    strings.add("");
                                    path.setProperties(strings);
                                } else {
                                    String originalRef = items.getString("originalRef");
                                    JSONObject property1 = getProperty(originalRef, definitions);

                                    JSONArray jsonArray = new JSONArray();
                                    jsonArray.add(property1);

                                    path.setProperties(jsonArray);
                                }
                            } else {

                                String originalRef = schema.getString("originalRef");

                                if (originalRef != null) {
                                    JSONObject property1 = getProperty(originalRef, definitions);

                                    path.setProperties(property1);
                                }
                            }
                        default:
                            break;
                    }

                }
            }
        }

        return tagList;
    }

    private JSONObject getProperty(String originalRef, JSONObject definitions) {
        JSONObject property = new JSONObject();
        JSONObject original = definitions.getJSONObject(originalRef);

        String type = original.getString("type");

        if ("object".equals(type)) {
            JSONObject properties = original.getJSONObject("properties");
            if (properties != null) {
                for (String propertyName : properties.keySet()) {
                    JSONObject propertyValue = properties.getJSONObject(propertyName);
                    String propertyType = propertyValue.getString("type");
                    String propertyExample = propertyValue.getString("example");
                    if ("string".equals(propertyType)) {
                        property.put(propertyName, propertyExample == null ? "" : propertyExample);
                    } else if ("integer".equals(propertyType)) {
                        property.put(propertyName, propertyExample == null ? 0 : propertyExample);
                    }
                }
            } else {
                System.out.println(originalRef + " 提取属性列表失败");
            }
        }
        return property;
    }

    private File generatoInterfacerWord(List<Tag> tagList, String modlueName) throws Exception {

        Document doc = ConfigUtil.getInterfaceHeaderTemplateDoc().deepClone();
        Document interfaceDoc = ConfigUtil.getInterfaceBodyTemplateDoc().deepClone();

        Map<String, Object> headerData = new HashMap();
        headerData.put("项目名称", modlueName);

        doc = WordUtil.fillWordByMap(doc, headerData);


        for (Tag tag : tagList) {
            Section lastSection = doc.getLastSection();
            Body body = lastSection.getBody();

            StyleCollection styles = doc.getStyles();
            Style style = styles.get("标题 2");
            body.appendParagraph(tag.getName()).getParagraphFormat().setStyle(style);

            List<Path> paths = tag.getPaths();
            for (Path path : paths) {

                Map<String, Object> data = new HashMap<String, Object>() {{
                    put("接口名称", path.getSummary());
                    put("接口地址", path.getPath());
                    put("方法", path.getMethod());
                    put("接口参数", path.getValue());
                    put("接口输出", path.getResponesValue());
                }};

                Document nodes = WordUtil.fillWordByMap(interfaceDoc, data);
                doc = WordUtil.mergeDocument(doc, nodes);
            }
        }

        doc.updateFields();// 更新域
        String dstDocName = "output" + File.separator + modlueName + "-接口设计文档.docx";
        doc.save(dstDocName);

        return new File(dstDocName);
    }

    @PostMapping("/generateInterfaceDocInXxsj")
    public ApiResult<String> generateInterfaceDocInXxsj(@RequestBody @Validated ServerUrlDTO serverUrlDTO) throws Exception {

        String serverUrl = serverUrlDTO.getUrl();
        List<ModuleItem> moduleList = getModuleList(serverUrl);

        List<File> files = new ArrayList<>();
        for (ModuleItem moduleItem : moduleList) {
            List<CategoryItem> categoryItemList = moduleItem.getCategoryList();
            Document outDoc = null;
            for (CategoryItem categoryItem : categoryItemList) {

                Map<String, Object> data = new HashMap<>();
                data.put("接口名称", categoryItem.getName());
                List<Map> interfaceList = new ArrayList<>();
                List<CategoryItem.Path> paths1 = categoryItem.getPaths();
                for (CategoryItem.Path path : paths1) {
                    Map<String, String> map = new HashMap<>();
                    map.put("接口名称", path.getSummary());
                    map.put("请求方式", path.getMethod());
                    map.put("接口地址", path.getUrl());
                    map.put("说明", path.getDescription());
                    interfaceList.add(map);
                }

                data.put("interfaceList", interfaceList);

                Document doc = ConfigUtil.getXxsjInterfaceBodyTemplateDoc().deepClone();
                Document tempDoc = WordUtil.fillWordByMap(doc, data);
                outDoc = WordUtil.mergeDocument(outDoc, tempDoc);
            }

            if (outDoc == null) {
                throw new AppException("没有生成的内容");
            }
            outDoc.updateFields();// 更新域
            String dstDocName = "output" + File.separator + moduleItem.getName() + "-详细设计文档接口部分.docx";
            outDoc.save(dstDocName);
            files.add(new File(dstDocName));
        }

        String fileName = serverUrl.replaceAll("[.:]", "_").replace("/", "");
        File zipFile = new File("output" + File.separator + fileName + "-详细设计文档接口部分.zip");
        ZipUtil.zipFiles(zipFile, files);

        for (File file : files) {
            Files.deleteIfExists(file.toPath());
        }
        return ApiResult.success(zipFile.getCanonicalPath());
    }

    private static List<ModuleItem> getModuleList(String serverUrl) {
        JSONArray response = HttpUtil.getForObject(serverUrl + "/swagger-resources", JSONArray.class);
        List<SwaggerResource> swaggerResources = response.toJavaList(SwaggerResource.class);
        List<ModuleItem> moduleItemList = new ArrayList<>();
        for (SwaggerResource swaggerResource : swaggerResources) {
            JSONObject apiDoc = HttpUtil.getForObject(serverUrl + swaggerResource.getUrl(), JSONObject.class);
            List<ApiDocTag> tags = apiDoc.getJSONArray("tags").toJavaList(ApiDocTag.class);
            List<CategoryItem> categoryItemList = tags.stream().map(item -> {
                CategoryItem categoryItem = new CategoryItem();
                categoryItem.setDescription(item.getDescription());
                categoryItem.setName(item.getName());
                categoryItem.setPaths(new ArrayList<>());
                return categoryItem;
            }).collect(Collectors.toList());

            JSONObject paths = apiDoc.getJSONObject("paths");
            Set<String> urlSet = paths.keySet();
            for (String url : urlSet) {
                JSONObject pathObject = paths.getJSONObject(url);

                for (String method : pathObject.keySet()) {

                    JSONObject methodObject = pathObject.getJSONObject(method);

                    JSONArray tags1 = methodObject.getJSONArray("tags");
                    List<String> tagStringList = tags1.toJavaList(String.class);
                    Optional<CategoryItem> first = categoryItemList.stream().filter(item -> tagStringList.contains(item.getName())).findFirst();
                    CategoryItem categoryItem;
                    if (first.isPresent()) {
                        // 不为空
                        categoryItem = first.get();
                    } else {
                        // 为空
                        Optional<CategoryItem> unknown = categoryItemList.stream().filter(item -> "未知分类".equals(item.getName())).findFirst();
                        if (unknown.isPresent()) {
                            categoryItem = unknown.get();
                        } else {
                            categoryItem = new CategoryItem();
                            categoryItem.setDescription("没有找到的分类");
                            categoryItem.setName("未知分类");
                            categoryItem.setPaths(new ArrayList<>());
                            categoryItemList.add(categoryItem);
                        }
                    }


                    String summary = methodObject.getString("summary");
                    String description = methodObject.getString("description");
                    JSONArray consumes1 = methodObject.getJSONArray("consumes");
                    List<String> consumes = new ArrayList<>();
                    if (consumes1 != null) {
                        consumes = consumes1.toJavaList(String.class);
                    }
                    JSONArray produces1 = methodObject.getJSONArray("produces");
                    List<String> produces = new ArrayList<>();
                    if (produces1 != null) {
                        produces = produces1.toJavaList(String.class);
                    }
                    Boolean deprecated = methodObject.getBoolean("deprecated");

                    CategoryItem.Path path = new CategoryItem.Path();
                    path.setUrl(url);
                    path.setMethod(method);
                    path.setSummary(summary);
                    path.setDescription(description);
                    path.setConsumes(consumes);
                    path.setProduces(produces);
                    path.setDeprecated(deprecated);
                    categoryItem.getPaths().add(path);
                }
            }

            ModuleItem moduleItem = new ModuleItem();
            moduleItem.setName(swaggerResource.getName());
            moduleItem.setCategoryList(categoryItemList);
            moduleItemList.add(moduleItem);
        }
        return moduleItemList;
    }
}
